package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

//import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
//import org.springframework.data.mongodb.repository.Aggregation;

@DubboService
public class MovementApiImpl implements  MovementApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TimeLineService timeLineService;


    @Override
    public String publish(Movement movement) {
        try {
            //设置PID
            movement.setPid(idWorker.getNextId("movement"));
            //设置时间
            movement.setCreated(System.currentTimeMillis());
            //1、保存动态详情
            mongoTemplate.save(movement);
//        //2、查询当前用户的好友数据
//        Criteria criteria =Criteria.where("userId").is(movement.getUserId());
//        Query query = Query.query(criteria);
//        List<Friend> friends = mongoTemplate.find(query, Friend.class);
//        //3、循环好友数据，构建时间线数据存入数据库
//        for (Friend friend : friends) {
//            MovementTimeLine movementTimeLine =new MovementTimeLine();
//            movementTimeLine.setMovementId(movement.getId());//获得动态id
//            movementTimeLine.setCreated(System.currentTimeMillis());//获得当前时间
//            movementTimeLine.setUserId(friend.getUserId());//获得用户id
//            movementTimeLine.setFriendId(friend.getFriendId());//获得用户朋友id
//            mongoTemplate.save(movementTimeLine);//循环添加效率低会被老板骂死
//        }
            timeLineService.saveTimeLine(movement.getUserId(),movement.getId());
        } catch (Exception e) {
            //忽略事务处理
            e.printStackTrace();
        }
        return movement.getId().toHexString();

    }

    @Override//查询个人动态
    public PageResult findByUserId(Integer page, Integer pagesize, Long userId) {
        Criteria criteria =Criteria.where("userId").is(userId).and("state").is(1);
        //skip是从哪里开始   limit表示查几条
        Query query =Query.query(criteria).skip((page -1 ) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
       return new PageResult(page,pagesize,  0,movements);
    }

    @Override//查看好友动态
    public PageResult findByFriendMovementsVo(Integer page, Integer pagesize, Long friendId ) {
        //先根据id查时间线表查出所有好友动态
        Criteria criteria =Criteria.where("friendId").is(friendId);
        Query query=Query.query(criteria);
        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query,MovementTimeLine.class);
//查出所有动态id
            List<ObjectId> movementIds = CollUtil.getFieldValues(movementTimeLines, "movementId", ObjectId.class);
        //再根据动态id查出所有动态
        Criteria criteria1 =Criteria.where("id").in(movementIds).and("state").is(1);
        Query query1 =Query.query(criteria1).skip((page -1 ) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query1, Movement.class);
        return new PageResult(page,pagesize,  0,movements);
    }

    //随机查询多条数据
    public PageResult randomMovements(Integer page, Integer pagesize) {
      //1,创建统计对象，设置统计参数
        TypedAggregation aggregation= Aggregation.newAggregation(Movement.class,Aggregation.sample(pagesize));
        //2.调用mongoTemplate方法统计
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);
        //3，获得统计结果
        List<Movement> movements = results.getMappedResults();
        return new PageResult(page,pagesize,0,movements);
    }

    //根据pid查询
    public PageResult findMovementsByPids(List<Long> pids, Integer page, Integer pagesize) {
        Criteria criteria =Criteria.where("pid").in(pids);
        Query query =Query.query(criteria).with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize,0,movements);
    }

    @Override
    public Movement findById(String movementId) {
        return mongoTemplate.findById(movementId,Movement.class);
    }

    @Override
    //查询用户所有动态
    public PageResult findAllByMovements(Integer page, Integer pagesize, Long uid, Integer state) {
        Query query=new Query();
         if(uid!=null){
             query.addCriteria(Criteria.where("userId").is(uid));
         }
         if(state!=null){
             query.addCriteria(Criteria.where("state").is(state));
         }
        long count = mongoTemplate.count(query, Movement.class);
         int count1=(int)count;
        query.with(Sort.by(Sort.Order.desc("created"))).skip((page-1)*pagesize).limit(pagesize);
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
         return new PageResult(page,pagesize,count1,movements);
    }

    @Override
    public void update(String movementId, int state) {
        Query query =Query.query(Criteria.where("Id").is(movementId));
        Update update=Update.update("state",state);
        mongoTemplate.updateFirst(query,update,Movement.class);
    }
}
